package com.yixing.demo.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@Component
public class UserOnlineStatus {
    ConcurrentHashMap<Integer, WebSocketSession> concurrentHashMap = new ConcurrentHashMap<>();
    
   public boolean online(Integer userId, WebSocketSession session) {
       if(concurrentHashMap.get(userId) != null) {
                log.info("已经登录过了，不能多开");
                return false;
       }else {
           concurrentHashMap.put(userId, session);
           log.info("上线");
           return true;
       }
   }

   public void offline(Integer userId, WebSocketSession session) {
       if(concurrentHashMap.get(userId) != session) {
           log.info("下线失败");
       }else {
           concurrentHashMap.remove(userId);
           log.info("下线");
       }
   }

   public WebSocketSession getWebSocketSessionByUserId(Integer userId) {
       return concurrentHashMap.get(userId);
   }
}
